package com.tronsis.distribution.activity.me.order;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.DeliveryBean;
import com.tronsis.distribution.bean.DeliveryDetailBean;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

public class DeliverDetailActivity extends ToolBarBaseActivity {
    @BindView(R.id.rv_goods)
    RecyclerView mRvGoods;
    @BindView(R.id.tv_more)
    TextView mTvMore;
    @BindView(R.id.tv_deliver_total_amount)
    TextView mTvDeliverTotalAmount;
    @BindView(R.id.tv_order_num)
    TextView mTvOrderNum;
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.rv_user_upload)
    RecyclerView mRvUserUpload;
    @BindView(R.id.tv_deliver_company)
    TextView mTvDeliverCompany;
    @BindView(R.id.tv_deliver_num)
    TextView mTvDeliverNum;
    @BindView(R.id.tv_deliver_real_amount)
    TextView mTvDeliverRealAmount;
    @BindView(R.id.ll_deliver_info)
    LinearLayout mLlDeliverInfo;


    private CommonAdapter mAdapter;
    private List<DeliveryDetailBean.ItemsBean> mGoodsList = new ArrayList<>();
    private List<DeliveryDetailBean.ItemsBean> mGoodsAllList = new ArrayList<>();
    private List<DeliveryDetailBean.ItemsBean> mGoodsPartList = new ArrayList<>();

    private ArrayList<ImageItem> mImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mPayImageAdapter;

    private DeliveryBean mAskBuyBean;
    private DeliveryDetailBean mAskBuyDetailBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver_detail);

        ButterKnife.bind(this);
        setTitle(true, getString(R.string.order_detail));

        initRv();
        initImageRv();

        mAskBuyBean = (DeliveryBean) getIntent().getSerializableExtra("DeliveryBean");
        if (mAskBuyBean != null) {
            httpGetDetail(mAskBuyBean.getId());
        }
    }

    private void initRv() {
        mAdapter = new CommonAdapter<DeliveryDetailBean.ItemsBean>(mContext, mGoodsList, R.layout.item_order_goods) {
            @Override
            protected void convert(ViewHolder holder, DeliveryDetailBean.ItemsBean bean, int position) {
                holder.setImageByUrl(mContext, R.id.iv_cover, Url.FILE_DOWNLOAD + bean.getCoverFid());
                holder.setText(R.id.tv_title, bean.getName());
                holder.setText(R.id.tv_count, "x" + bean.getAmount());
                holder.setVisible(R.id.tv_note, true);
                if (TextUtils.isEmpty(bean.getRemarks())) {
                    holder.setVisible(R.id.tv_note, false);
                }else {
                    holder.setVisible(R.id.tv_note, true);
                    holder.setText(R.id.tv_note,"备注："+bean.getRemarks());
                }
            }
        };


        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvGoods.addItemDecoration(decoration);
        mRvGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mRvGoods.setHasFixedSize(true);
        mRvGoods.setNestedScrollingEnabled(false);
        mRvGoods.setAdapter(mAdapter);
    }

    private void initImageRv() {
        mPayImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = holder.getView(R.id.iv_item);
                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }

                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mImageList.get(position).path) && TextUtils.isEmpty(mImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });
            }


        };


        mRvUserUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvUserUpload.setAdapter(mPayImageAdapter);
        mRvUserUpload.setHasFixedSize(true);
        mRvUserUpload.setNestedScrollingEnabled(false);
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        switch (paramId) {
            case RIGHT_TEXT:

                break;
            default:
                break;
        }

    }

    @OnClick(R.id.tv_more)
    void onMoreClick() {
        if (mGoodsList.size() > 6) {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsPartList);
            mTvMore.setText(getString(R.string.format_view_all_goods, mGoodsAllList.size()));
        } else {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsAllList);
            mTvMore.setText("收起");
        }

        mAdapter.notifyDataSetChanged();
    }

    private void setDetailView(DeliveryDetailBean detailBean) {
        if (detailBean == null) {
            return;
        }


        if (TextUtils.isEmpty(detailBean.getExpressCode())) {
            mLlDeliverInfo.setVisibility(View.GONE);
        } else {
            mLlDeliverInfo.setVisibility(View.VISIBLE);
            mTvDeliverCompany.setText(getString(R.string.format_deliver_company, detailBean.getExpressInc()));
            mTvDeliverNum.setText(getString(R.string.format_deliver_company, detailBean.getExpressCode()));
            mTvDeliverRealAmount.setText(getString(R.string.format_deliver_real_amount, detailBean.getRealFreight()));

            String fid = detailBean.getExpressFid();
            mImageList.clear();
            mImageList.addAll(CommonUtil.getSplitImage(fid));
            mPayImageAdapter.notifyDataSetChanged();
        }

        mTvOrderNum.setText(getString(R.string.format_order_num, detailBean.getCode()));
        mTvOrderTime.setText(getString(R.string.format_order_time, DateUtil.getDateTimeString(detailBean.getCreatedOn())));
        mTvDeliverTotalAmount.setText(getString(R.string.format_rmb, detailBean.getTotalFreight()));

        DeliveryDetailBean.ReceiverAddrBean receiverAddr = detailBean.getReceiverAddr();
        if (receiverAddr != null) {
            mTvName.setText(getString(R.string.format_deliver_name, receiverAddr.getName()));
            mTvPhone.setText(receiverAddr.getPhone());
            mTvAddress.setText(CommonUtil.getRegionString(receiverAddr.getRegion())+ receiverAddr.getDetail());
        }

        List<DeliveryDetailBean.ItemsBean> items = detailBean.getItems();
        mTvMore.setText(getString(R.string.format_view_all_goods, mGoodsAllList.size()));
        mGoodsList.clear();
        mGoodsAllList.clear();
        mGoodsAllList.addAll(items);
        if (mGoodsAllList.size() > 6) {
            mTvMore.setVisibility(View.VISIBLE);
            for (int i = 0; i < 6; i++) {
                mGoodsPartList.add(mGoodsAllList.get(i));
            }
            mGoodsList.addAll(mGoodsPartList);
        } else {
            mGoodsList.addAll(mGoodsAllList);
        }
        mAdapter.notifyDataSetChanged();
    }


    private void httpGetDetail(String deliveryId) {
        try {
            OrderBizFactory.createBiz().getDeliveryDetail(this, deliveryId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    mAskBuyDetailBean = (DeliveryDetailBean) data;
                    setDetailView(mAskBuyDetailBean);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


}
